package com.pda.yuanjing.pages.login;

import android.content.Context;
import android.content.SharedPreferences;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.telephony.TelephonyManager;

import com.apkfuns.logutils.LogUtils;
import com.pda.yuanjing.PDApp;
import com.pda.yuanjing.beanin.DownBaseBeanIn;
import com.pda.yuanjing.beanin.LoginBeanIn;
import com.pda.yuanjing.beanout.CidInfoBeanOut;
import com.pda.yuanjing.beanout.DealerBeanOut;
import com.pda.yuanjing.beanout.GYSBeanOut;
import com.pda.yuanjing.beanout.LoginBeanOut;
import com.pda.yuanjing.beanout.LogoBeanOut;
import com.pda.yuanjing.beanout.PPBeanOut;
import com.pda.yuanjing.beanout.ProductBeanOut;
import com.pda.yuanjing.beanout.StoreBeanOut;
import com.public_module.basemvp.model.BaseModel;
import com.public_module.config.ApiYJ;
import com.public_module.config.SetConfig;
import com.public_module.tools.SharedPreferencesManger;
import com.public_module.tools.StringProcess;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;

public class LoginModelImpl extends BaseModel implements LoginModel {
    private String tag = "LoginModelImpl";
    private LoginBeanOut loginBeanOut = null;
    private LogoBeanOut logoBeanOut = null;
    public LoginModelImpl(Context context) {
        super(context);
    }

    public static String getUUID(){
        if(SharedPreferencesManger.getuuid().length()==0){
            String uuid = UUID.randomUUID().toString();
            SharedPreferencesManger.setuuid(uuid);
        }
        return SharedPreferencesManger.getuuid();
    }

    @Override
    public void login(String url ,String username, String password, String sn, final CallBack callBack) {
        try {
                api = new Retrofit.Builder()
                    .baseUrl("http://" + url + "/")
                    .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                    .client(client)
                    .build().create(ApiYJ.class);

            apisync = new Retrofit.Builder()
                    .baseUrl("http://"+ url+"/")
                    .client(client)
                    .build().create(ApiYJ.class);

            LoginBeanIn loginBeanIn = new LoginBeanIn();
            loginBeanIn.setAction("Login");
            loginBeanIn.setSn(getUUID());
            loginBeanIn.setCid(SharedPreferencesManger.getCid());
            loginBeanIn.setUserName(username);
            loginBeanIn.setPassword(password);
            loginBeanIn.setLx("lx");

            RequestBody body = RequestBody.create(SetConfig.JSON, gson.toJson(loginBeanIn));
            api.login(body)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new io.reactivex.Observer<ResponseBody>() {
                        private Disposable mDisposable;

                        @Override
                        public void onSubscribe(Disposable d) {
                            mDisposable = d;
                        }

                        @Override
                        public void onComplete() {
                            SharedPreferencesManger.setUname(username);
                            SharedPreferencesManger.setUpass(password);
                            SharedPreferencesManger.setUid(loginBeanOut.getData().getUserID());
                            SharedPreferencesManger.setStoreID(loginBeanOut.getData().getStoreID());
                            SharedPreferencesManger.setStoreCode(loginBeanOut.getData().getStoreCode());
                            SharedPreferencesManger.setStoreName(loginBeanOut.getData().getStoreName());
                            SharedPreferencesManger.setRealName(loginBeanOut.getData().getUserName());
                            SharedPreferencesManger.setZdyjd(loginBeanOut.getData().isAllowCreateJieDianBill());
                            int res1 = downLoadInfo1();
                            int res2 = downLoadInfo2();
                            int res3 = downLoadInfo3();
                            int res4 = downLoadInfo4();
                            int res5 = downLoadInfo5();
                            int res6 = downLoadInfo6();

                            if(res1==0 && res2==0 && res3==0 && res4==0 && res5==0 && res6==0){
//                                List<LoginBeanOut.DataBean.ShowInfoBean> listt = new ArrayList<>();
//                                if(!loginBeanOut.getData().isAllowCreateJieDianBill()){
//                                    for (int i = 0; i <loginBeanOut.getData().getShowInfo().size() ; i++) {
//                                        if(loginBeanOut.getData().getShowInfo().get(i).getList().get(0).getId()<100){
//                                            listt.add(loginBeanOut.getData().getShowInfo().get(i));
//                                        }
//                                    }
//                                    callBack.onloginSuccess(listt);
//                                }else{
//                                    callBack.onloginSuccess(loginBeanOut.getData().getShowInfo());
//                                }
                                callBack.onloginSuccess(loginBeanOut.getData().getShowInfo());
                            }else {
                                callBack.onFail("基础数据获取失败");
                            }
                            mDisposable.dispose();
                        }

                        @Override
                        public void onError(Throwable e) {
                            if (loginBeanOut != null && loginBeanOut.getErrmsg() != null) {
                                callBack.onFail(loginBeanOut.getErrmsg());
                            } else {
                                callBack.onFail(SetConfig.connectError);
                            }
                            mDisposable.dispose();
                        }

                        @Override
                        public void onNext(ResponseBody abBean) {
                            LogUtils.w(StringProcess.responsetoString(abBean));
                            loginBeanOut = gson.fromJson(StringProcess.responsetoString(abBean), LoginBeanOut.class);
                            if (loginBeanOut != null && loginBeanOut.getErrcode() == 0) {
                                onComplete();
                            } else {
                                onError(new Throwable());
                            }
                        }
                    });
        } catch (Exception e) {
            callBack.onFail(SetConfig.connectError);
            e.printStackTrace();
        }
    }

    @Override
    public void logo(String url, final CallBack callBack) {
        try {
            api = new Retrofit.Builder()
                    .baseUrl("http://" + url + "/")
                    .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                    .client(client)
                    .build().create(ApiYJ.class);

            LoginBeanIn loginBeanIn = new LoginBeanIn();
            loginBeanIn.setAction("DownloadLogo");
            loginBeanIn.setCid(SharedPreferencesManger.getCid());
            RequestBody body = RequestBody.create(SetConfig.JSON, gson.toJson(loginBeanIn));
            api.login(body)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new io.reactivex.Observer<ResponseBody>() {
                        private Disposable mDisposable;

                        @Override
                        public void onSubscribe(Disposable d) {
                            mDisposable = d;
                        }

                        @Override
                        public void onComplete() {
                            callBack.onloginLogo(logoBeanOut.getData());
                            mDisposable.dispose();
                        }

                        @Override
                        public void onError(Throwable e) {
                            mDisposable.dispose();
                        }

                        @Override
                        public void onNext(ResponseBody abBean) {
                            LogUtils.w(StringProcess.responsetoString(abBean));
                            logoBeanOut = gson.fromJson(StringProcess.responsetoString(abBean), LogoBeanOut.class);
                            if (logoBeanOut != null && logoBeanOut.getErrcode() == 0) {
                                onComplete();
                            } else {
                                onError(new Throwable());
                            }
                        }
                    });
        } catch (Exception e) {
            callBack.onFail(SetConfig.connectError);
            e.printStackTrace();
        }
    }

    public int downLoadInfo1() {
        try {
            PDApp.productBeanOut.setErrcode(-1);
            DownBaseBeanIn downBaseBeanIn = new DownBaseBeanIn();
            downBaseBeanIn.setAction("DownloadBaseInfo");
            downBaseBeanIn.setCid(SharedPreferencesManger.getCid());
            downBaseBeanIn.setUserID(SharedPreferencesManger.getUid());
            downBaseBeanIn.setStoreID(SharedPreferencesManger.getStoreID());
            downBaseBeanIn.setBaseType("1");
            RequestBody body = RequestBody.create(SetConfig.JSON, gson.toJson(downBaseBeanIn));
            final Call<ResponseBody> call = apisync.downLoad(body);
            Thread thread = new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        Response<ResponseBody> response = call.execute();
                        if (response.isSuccessful()) {
                            //LogUtils.e(StringProcess.responsetoString(response.body()));
                            PDApp.productBeanOut = gson.fromJson(StringProcess.responsetoString(response.body()), ProductBeanOut.class);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
            thread.start();
            thread.join();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            return PDApp.productBeanOut.getErrcode();
        }
    }

    public int downLoadInfo2() {
        try {
            PDApp.storeBeanOut.setErrcode(-1);
            DownBaseBeanIn downBaseBeanIn = new DownBaseBeanIn();
            downBaseBeanIn.setAction("DownloadBaseInfo");
            downBaseBeanIn.setCid(SharedPreferencesManger.getCid());
            downBaseBeanIn.setUserID(SharedPreferencesManger.getUid());
            downBaseBeanIn.setStoreID(SharedPreferencesManger.getStoreID());
            downBaseBeanIn.setBaseType("2");
            RequestBody body = RequestBody.create(SetConfig.JSON, gson.toJson(downBaseBeanIn));
            final Call<ResponseBody> call = apisync.downLoad(body);
            Thread thread = new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        Response<ResponseBody> response = call.execute();
                        if (response.isSuccessful()) {
                            //LogUtils.e(StringProcess.responsetoString(response.body()));
                            PDApp.storeBeanOut = gson.fromJson(StringProcess.responsetoString(response.body()), StoreBeanOut.class);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
            thread.start();
            thread.join();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            return PDApp.storeBeanOut.getErrcode();
        }
    }

    public int downLoadInfo3() {
        try {
            PDApp.dealerBeanOut.setErrcode(-1);
            DownBaseBeanIn downBaseBeanIn = new DownBaseBeanIn();
            downBaseBeanIn.setAction("DownloadBaseInfo");
            downBaseBeanIn.setCid(SharedPreferencesManger.getCid());
            downBaseBeanIn.setUserID(SharedPreferencesManger.getUid());
            downBaseBeanIn.setStoreID(SharedPreferencesManger.getStoreID());
            downBaseBeanIn.setBaseType("3");
            RequestBody body = RequestBody.create(SetConfig.JSON, gson.toJson(downBaseBeanIn));
            final Call<ResponseBody> call = apisync.downLoad(body);
            Thread thread = new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        Response<ResponseBody> response = call.execute();
                        if (response.isSuccessful()) {
                            //LogUtils.e(StringProcess.responsetoString(response.body()));
                            PDApp.dealerBeanOut = gson.fromJson(StringProcess.responsetoString(response.body()), DealerBeanOut.class);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
            thread.start();
            thread.join();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            return PDApp.dealerBeanOut.getErrcode();
        }
    }

    public int downLoadInfo6() {
        try {
            PDApp.gysBeanOut.setErrcode(-1);
            DownBaseBeanIn downBaseBeanIn = new DownBaseBeanIn();
            downBaseBeanIn.setAction("DownloadBaseInfo");
            downBaseBeanIn.setCid(SharedPreferencesManger.getCid());
            downBaseBeanIn.setUserID(SharedPreferencesManger.getUid());
            downBaseBeanIn.setStoreID(SharedPreferencesManger.getStoreID());
            downBaseBeanIn.setBaseType("4");
            RequestBody body = RequestBody.create(SetConfig.JSON, gson.toJson(downBaseBeanIn));
            final Call<ResponseBody> call = apisync.downLoad(body);
            Thread thread = new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        Response<ResponseBody> response = call.execute();
                        if (response.isSuccessful()) {
                            //LogUtils.e(StringProcess.responsetoString(response.body()));
                            PDApp.gysBeanOut = gson.fromJson(StringProcess.responsetoString(response.body()), GYSBeanOut.class);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
            thread.start();
            thread.join();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            return PDApp.gysBeanOut.getErrcode();
        }
    }

    public int downLoadInfo4() {
        try {
            PDApp.cidInfoBeanOut.setErrcode(-1);
            DownBaseBeanIn downBaseBeanIn = new DownBaseBeanIn();
            downBaseBeanIn.setAction("DownloadConfig");
            downBaseBeanIn.setCid(SharedPreferencesManger.getCid());
            downBaseBeanIn.setUserID(SharedPreferencesManger.getUid());
            downBaseBeanIn.setStoreID(SharedPreferencesManger.getStoreID());
            RequestBody body = RequestBody.create(SetConfig.JSON, gson.toJson(downBaseBeanIn));
            final Call<ResponseBody> call = apisync.downLoad(body);
            Thread thread = new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        Response<ResponseBody> response = call.execute();
                        if (response.isSuccessful()) {
                            //LogUtils.e(StringProcess.responsetoString(response.body()));
                            PDApp.cidInfoBeanOut = gson.fromJson(StringProcess.responsetoString(response.body()), CidInfoBeanOut.class);
                            if(PDApp.cidInfoBeanOut.getData()==null){
                                PDApp.cidInfoBeanOut.setErrcode(-1);
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
            thread.start();
            thread.join();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            return PDApp.cidInfoBeanOut.getErrcode();
        }
    }

    public int downLoadInfo5() {
        try {
            PDApp.ppBeanOut.setErrcode(-1);
            DownBaseBeanIn downBaseBeanIn = new DownBaseBeanIn();
            downBaseBeanIn.setAction("SY_QueryProcess");
            downBaseBeanIn.setCid(SharedPreferencesManger.getCid());
            downBaseBeanIn.setUserID(SharedPreferencesManger.getUid());
            downBaseBeanIn.setStoreID(SharedPreferencesManger.getStoreID());
            RequestBody body = RequestBody.create(SetConfig.JSON, gson.toJson(downBaseBeanIn));
            final Call<ResponseBody> call = apisync.downLoad(body);
            Thread thread = new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        Response<ResponseBody> response = call.execute();
                        if (response.isSuccessful()) {
                            //LogUtils.e(StringProcess.responsetoString(response.body()));
                            PDApp.ppBeanOut = gson.fromJson(StringProcess.responsetoString(response.body()), PPBeanOut.class);
                            if(PDApp.ppBeanOut.getData()==null || PDApp.ppBeanOut.getData().size()==0){
                                PDApp.ppBeanOut.setErrcode(-1);
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
            thread.start();
            thread.join();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            return PDApp.cidInfoBeanOut.getErrcode();
        }
    }

}

